package personal.zq.practice.common.utils.leetcode.medium;

/**
 * 求中位数2
 *
 * @author zhangqing
 * @version 1.0
 * @date 2022/6/21
 */
class Median2 {
    public static void main(String[] args) {
        System.out.println(findMedianSortedArrays(new int[]{1, 3}, new int[]{2}) + "");
        System.out.println(findMedianSortedArrays(new int[]{1, 2}, new int[]{3, 4}) + "");
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int l = nums1.length + nums2.length;
        boolean f = l % 2 == 0;
        int i = 0, j = 0;
        double m = 0;
        for (int k = 0; k <= l / 2; k++) {
            int me;
            if (i == nums1.length || (i < nums1.length && j < nums2.length && nums1[i] > nums2[j])) {
                me = nums2[j];
                j++;
            } else {
                me = nums1[i];
                i++;
            }
            if (f) {
                if (k == (l / 2) - 1) {
                    int me2;
                    if (i == nums1.length || (i < nums1.length && j < nums2.length && nums1[i] > nums2[j])) {
                        me2 = nums2[j];
                    } else {
                        me2 = nums1[i];
                    }
                    m = (me + me2) / 2.0;
                    break;
                }
            } else {
                if (k == (l / 2)) {
                    m = me;
                    break;
                }
            }
        }
        return m;
    }
}
